package mysql

import "gorm.io/gorm"

type Order struct {
	gorm.Model
	UserId  int     `gorm:"type:int;not null; commit:'用户ID'"`
	OrderId string  `gorm:"type:varchar(50);not null; commit:'订单号'"`
	Amount  float64 `gorm:"type:decimal(10,2);not null; commit:'总金额'"`
	Payment string  `gorm:"type:enum('微信','支付宝');not null; commit:'支付方式'"`
	Status  string  `gorm:"type:enum('未支付','已支付');not null; commit:'订单状态'"`
}

type OrderGoods struct {
	gorm.Model
	OrderId int     `gorm:"type:int;not null; commit:'订单ID'"`
	GoodsId int     `gorm:"type:int;not null; commit:'商品ID'"`
	Title   string  `gorm:"type:varchar(20);not null; commit:'商品标题'"`
	Price   float64 `gorm:"type:decimal(10,2);not null; commit:'商品价格'"`
	Cover   string  `gorm:"type:varchar(255);not null; commit:'商品封面'"`
	Stock   int     `gorm:"type:int(10);not null; commit:'商品库存'"`
	Status  string  `gorm:"type:enum('已上架','未上架');not null; commit:'商品状态'"`
	Likes   int64   `gorm:"type:int(10);not null; commit:'商品点赞数'"`
	Type    string  `gorm:"type:enum('数码','水果');not null; commit:'商品类型'"`
}

func (o *Order) List() (order []*Order) {
	DB.Debug().Find(&order)
	return
}

func CreateAnimals(o *Order, og *OrderGoods) error {
	// 再唠叨一下，事务一旦开始，你就应该使用 tx 处理数据
	tx := DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err = tx.Error; err != nil {
		return err
	}

	if err = tx.Create(&o).Error; err != nil {
		tx.Rollback()
		return err
	}
	og.OrderId = int(o.ID)
	if err = tx.Create(&og).Error; err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}
func (o *Order) OrderStarts(Id string, Status string) (order []*Order) {
	DB.Model(&order).Where("order_id", Id).Update("status", Status).Find(&order)
	return
}
